package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.QuestionManageDao;
import com.itheima.entity.PageResult;
import com.itheima.exceptions.BusinessException;
import com.itheima.pojo.Question;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author W.J.Y
 */
@Service(version = "1.0.0",interfaceClass = QuestionManageService.class)
@Transactional
public class QuestionManageServiceImpl implements QuestionManageService {

    @Resource
    private QuestionManageDao questionManageDao;

    /**
     * 查询全部题目信息
     * @return  全部题目信息
     */
    @Override
    public List<Question> findAll() {
        List<Question> questions0 = questionManageDao.find0All();
        return questions0;
    }


    /**
     * 添加题目
     * @param question  题目实例
     * @throws BusinessException    可能出现的业务异常
     */
    @Override
    public void add(Question question) throws BusinessException {
        Integer count = questionManageDao.findQuestionByName(question);
        if(count>0){
            throw new BusinessException("已存在相同名称的题目，添加失败！");
        }
        questionManageDao.add(question);
    }


    /**
     * 编辑题目
     * @param question  题目实例
     * @throws BusinessException    可能出现的业务异常
     */
    @Override
    public void update(Question question)  throws BusinessException{
        Integer count = questionManageDao.findQuestionByName(question);
            questionManageDao.update0(question);
    }

    /**
     * 根据ID删除题目
     * @param id    题目ID
     * @throws BusinessException    可能出现的业务异常
     */
    @Override
    public void delete(int id)  throws BusinessException{
        //首先检查题目与问卷关联关系
/*        int count = questionManageDao.findCountByQuestionId(id);
        if (count > 0 ){
            throw new BusinessException("删除失败，该题目已被问卷关联，请先解除关联关系！");
        }*/
        questionManageDao.delete(id);
    }

    /**
     * 根据ID查询题目信息
     * @param id    题目ID
     * @return  题目实例
     */
    @Override
    public Question findById(int id) {
        return questionManageDao.findById(id);
    }

    /**
     * 分页查询题目信息
     * @param currentPage   当前页码
     * @param pageSize  每页条数
     * @param queryString   查询语句
     * @return  分页题目信息
     */
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //开启分页查询
        PageHelper.startPage(currentPage,pageSize);
        //调用dao层查询语句
        Page<Question> page = questionManageDao.findPage(queryString);
        //封装分页查询结果对象
        return new PageResult(page.getTotal(),page.getResult());
    }
}
